import { Platform, PermissionsAndroid, Alert } from 'react-native';
import RNFS from 'react-native-fs2';
import { CameraRoll } from "@react-native-camera-roll/camera-roll";
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';

const androidVersion = typeof Platform.Version === 'string' ? parseInt(Platform.Version, 10) : Platform.Version;

async function requestAndroidPermission(): Promise<boolean> {
    if (androidVersion >= 33) {
        const permissions = [
            PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES,
            PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO
        ];

        const granted = await PermissionsAndroid.requestMultiple(permissions);
        return (
            granted[PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES] === PermissionsAndroid.RESULTS.GRANTED &&
            granted[PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO] === PermissionsAndroid.RESULTS.GRANTED
        );
    } else {
        const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
        return granted === PermissionsAndroid.RESULTS.GRANTED;
    }
}

async function hasAndroidPermission(): Promise<boolean> {
    if (androidVersion >= 33) {
        const hasImages = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES);
        const hasVideo = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO);
        if (hasImages && hasVideo) return true;
    } else {
        const hasStorage = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
        if (hasStorage) return true;
    }
    return requestAndroidPermission();
}

async function hasIOSPermission(): Promise<boolean> {
    const result = await check(PERMISSIONS.IOS.PHOTO_LIBRARY);
    if (result === RESULTS.GRANTED) return true;

    const requestResult = await request(PERMISSIONS.IOS.PHOTO_LIBRARY);
    return requestResult === RESULTS.GRANTED;
}

export const saveImageToAlbum = async (imageUrl: string): Promise<void> => {

    try {
        const hasPermission = Platform.OS === 'android'
            ? await hasAndroidPermission()
            : await hasIOSPermission();

        if (!hasPermission) {
            Alert.alert('权限被拒绝', '请在设置中开启存储或相册权限');
            return;
        }

        const fileName = imageUrl.split('/').pop() || `image_${Date.now()}.png`;
        const localPath = `${RNFS.CachesDirectoryPath}/${fileName}`;

        const result = await RNFS.downloadFile({
            fromUrl: imageUrl,
            toFile: localPath,
        }).promise;

        if (result.statusCode === 200) {
            await CameraRoll.save(localPath, { type: 'photo' });
            Alert.alert('保存成功', '图片已保存到相册');
        } else {
            throw new Error(`下载失败，状态码 ${result.statusCode}`);
        }
    } catch (error) {
        console.error('保存失败:', error);
        Alert.alert('保存失败', '图片保存过程中出现错误，请稍后再试');
    }
};